<?php


namespace wechat\lib\core;


use wechat\lib\Cache;
use wechat\lib\Http;

class Base implements IResponseCode
{
    /**
     * @desc 微信 服务号|订阅号 appid
     * @var bool|string
     */
    protected $appid;

    /**
     * @desc 微信 服务号|订阅号 appsecret
     * @var bool|string
     */
    protected $appsecret;

    /**
     * @desc 获取全局access_token
     * @return string
     */
    protected function getGlobalAccessToken():string
    {
        $arr = json_decode(Cache::cache('globalaccesstoken'),true);
        $str = Cache::cache('globalaccesstoken');

        if ($arr['timeout']&&$arr['timeout']<time()){
            $str = $this->globalAccessToken($this->appid,$this->appsecret);
        }

        if(!$arr||!array_key_exists('access_token',$arr)){
            $str = $this->globalAccessToken($this->appid,$this->appsecret);
        }
        $res = $this->checkError($str);
        if ($res){
            return json_decode($str,true)['access_token'];
        }
        return false;

    }

    private function globalAccessToken(string $appid, string $appsecret):string
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";
        $str = Http::curl('get',$url);
        Cache::cache('globalaccesstoken',$str);
        return $str;
    }

    public function checkError(string $response)
    {
        $arr = json_decode($response,true);
        try{
            if(array_key_exists('errcode',$arr)&&$arr['errcode']!=0){
                $msg = IResponseCode::RESPONSE_CODE[$arr['errcode']];
                throw new \Exception($msg,$arr['errcode']);
            }
        }catch (\Exception $e){
            $err_arr = array_reverse(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))[0];
            echo '错误原因: "'.$e->getMessage().'" 微信错误码: ('.$e->getCode().')</br>';
            echo $err_arr['file'].'::'.$err_arr['line'];
            die();
        }

        return true;
    }

    /**
     * @desc 报错
     * @param string $msg
     */
    protected function error(string $msg)
    {
        try{
            throw new \Exception($msg);
        }catch (\Exception $e){
            $err_arr = array_reverse(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))[0];
            echo '错误原因: "'.$e->getMessage().'"</br>';
            echo $err_arr['file'].'::'.$err_arr['line'];
            die();
        }
    }

    /**
     * @desc 验证php扩展
     * @param string $path
     * @param array $arr
     * @return bool
     */
    protected function extension(string $path, array $arr):bool
    {
        $extension = pathinfo($path,PATHINFO_EXTENSION );
        if (!is_file($path)){
            return false;
        }
        foreach ($arr as $v){
            if($extension==$v){
                return true;
            }
        }
        return false;
    }
}